package com.adgroup.doremon_ad;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;
import java.net.UnknownHostException;
import java.util.ArrayList;

import javax.crypto.spec.IvParameterSpec;

import model.film;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


import adapter.AdapterVideo;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class loadvideo {
//	public class loadvideo extends AsyncTask<Void, Void, Boolean> {

	String TAG_DATA = "data";
	String TAG_ITEMS = "items";
	String TAG_VIDEO = "video";
	String TAG_IDVIDEO = "id";
	String TAG_TITLE = "title";
	String TAG_DURATION = "duration";
	String TAG_THUMBNAIL = "thumbnail";
	String TAG_TMUMBSQDEFAULT = "sqDefault";

	public String urllinkllk;
	ArrayList<film> films;
	AdapterVideo adapter;
	boolean loadmore;
	String idchannel;
	int max_count_video = 10;
	View footer;
	ImageView nodata;
	TextView count;
	public loadvideo(AdapterVideo adapter, boolean loadmore, String urllinkllk,
			ArrayList<film> films, View footer, ImageView nodata, TextView count) {
		this.adapter = adapter;
		this.loadmore = loadmore;
		this.urllinkllk = urllinkllk;
		this.films = films;
		this.footer = footer;
		this.nodata = nodata;
		this.count=count;
	}

	boolean unknowhost = false;

//	@Override
//	protected void onPreExecute() {
//		// TODO Auto-generated method stub
//		super.onPreExecute();
//		footer.setVisibility(View.VISIBLE);
//		nodata.setVisibility(View.INVISIBLE);
//		unknowhost = false;
//		try {
//			if (!loadmore) {
//				films.clear();
//				adapter.films.clear();
//			}
//		} catch (Exception e) {
//			// TODO: handle exception
//		}
//	}
//
//	@Override
//	protected Boolean doInBackground(Void... arg0) {
//		// TODO Auto-generated method stub
//		boolean flag = false;
//		URL url;
//		URLConnection conn;
//		boolean f = false;
//		try {
//			url = new URL(urllinkllk);
//			conn = url.openConnection();
//			conn.setConnectTimeout(5000); // set timeout to 5 seconds
//			InputStream is = conn.getInputStream();
////			InputStream inputStream = .getResources().openRawResource(R.raw.json);
//			// read
//			BufferedReader reader = new BufferedReader(new InputStreamReader(
//					is, "utf-8"));
//			String line = null;
//			String data = "";
//			while ((line = reader.readLine()) != null) {
//				data += line;
//			}
//			is.close();
//
//			// add to josnobject
//			JSONObject jObj = new JSONObject(data);
//			JSONObject jData = jObj.getJSONObject(TAG_DATA);
//			JSONArray jItems = jData.getJSONArray(TAG_ITEMS);
//			// Log.d("item",jItems.length()+"");
//			for (int i = 0; i < jItems.length(); i++) {
//				JSONObject item = jItems.getJSONObject(i);
//				JSONObject jVideo = item.getJSONObject(TAG_VIDEO);
//				String title = jVideo.getString(TAG_TITLE);
//				String duration = jVideo.getString(TAG_DURATION);
//
//				JSONObject jThumb = jVideo.getJSONObject(TAG_THUMBNAIL);
//				String thumb = jThumb.getString(TAG_TMUMBSQDEFAULT);
//
//				String idvideo = jVideo.getString(TAG_IDVIDEO);
//
//				film video = new film(title, thumb, idvideo, duration);
//
//				films.add(video);
//			}
//
//			flag = true;
//		} catch (UnknownHostException ex) {
//			unknowhost = true;
//		} catch (Exception e) {
//		}
//		return flag;
//	}
//
//	@Override
//	protected void onPostExecute(Boolean result) {
//		// TODO Auto-generated method stub
//		super.onPostExecute(result);
//		footer.setVisibility(View.INVISIBLE);
//		
//		if (result && !unknowhost) {
//			try {
//				count.setText(films.size()+" film");
//				adapter.films = films;
//				adapter.notifyDataSetChanged();
//			} catch (Exception e) {
//				// TODO: handle exception
//			}
//		} else {
//			nodata.setVisibility(View.VISIBLE);
//		}
//	}
	class MyAsynTask extends AsyncTask<Void, Void, String>
    {

		@Override
		protected String doInBackground(Void... params) {
			URL url;
			URLConnection conn;
			try {
				url = new URL(urllinkllk);
				conn = url.openConnection();
				InputStream is = conn.getInputStream();
				
				//read
				BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"));
				String line = null;
				String data = "";
				while ((line=reader.readLine())!=null){
					data += line;
				}
				is.close();
				
				return data;
				
			} catch (Exception e) {
				Log.e(TAG_DATA, e.getMessage());
			}
			return "";
		}

		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			// add to josnobject
			if(result==""){
				footer.setVisibility(View.INVISIBLE);
				adapter.notifyDataSetChanged();
			}
			else{
			JSONObject jObj;
			try {
				jObj = new JSONObject(result);
				JSONObject jData = jObj.getJSONObject(TAG_DATA);
				JSONArray jItems = jData.getJSONArray(TAG_ITEMS);
				// Log.d("item",jItems.length()+"");
				for (int i = 0; i < jItems.length(); i++) {
					JSONObject item = jItems.getJSONObject(i);
					JSONObject jVideo = item.getJSONObject(TAG_VIDEO);
					String title = jVideo.getString(TAG_TITLE);
					String duration = jVideo.getString(TAG_DURATION);
					System.out.println("Run dat n� 2 " +duration);
					JSONObject jThumb = jVideo.getJSONObject(TAG_THUMBNAIL);
					String thumb = jThumb.getString(TAG_TMUMBSQDEFAULT);

					String idvideo = jVideo.getString(TAG_IDVIDEO);

					film video = new film(title, thumb, idvideo, duration);

					films.add(video);
				}
				
				//flag = true;
				
				footer.setVisibility(View.INVISIBLE);
				
				if (true && !unknowhost) {
					try {
						if(films.size()==0){
							MainActivity.n++;
						}
						count.setText(films.size()+" films");
						//adapter.films = films;
						adapter.notifyDataSetChanged();
						MainActivity.loadmore = true;
					} catch (Exception e) {
						// TODO: handle exception
					}
				} else {
					nodata.setVisibility(View.VISIBLE);
				}
			}catch (JSONException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
				if(MainActivity.n<MainActivity.video.size()-1){
					MainActivity.n++;
				}
				urllinkllk = "https://gdata.youtube.com/feeds/api/playlists/"
						+ MainActivity.video.get(MainActivity.n).getVideoID()
						+ "?alt=jsonc&v=2&start-index="
						+ 1
						+ "&max-results=" + max_count_video;
				System.out.println("ON scROLL " + urllinkllk);
				Log.d("logTage", urllinkllk);
//				new loadvideo(adapter, true, urlllk, films, footer, nodata, count)
//						.execute();
				footer.setVisibility(View.VISIBLE);
				nodata.setVisibility(View.INVISIBLE);
				unknowhost = false;
				try {
					if (!loadmore) {
						films.clear();
						adapter.films.clear();
					}
				} catch (Exception e) {
					// TODO: handle exception
				}
				
				System.out.println("Run dat n� 1 ");
				boolean flag = false;
				InputStream is = null; 
				new MyAsynTask().execute();
			}
			} 
			
		}
    	
    }
	public ArrayList<film> loadvideo(Context context,String filename) throws IOException, JSONException {
		footer.setVisibility(View.VISIBLE);
		nodata.setVisibility(View.INVISIBLE);
		unknowhost = false;
		try {
			if (!loadmore) {
				films.clear();
				adapter.films.clear();
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		System.out.println("Run dat n� 1 ");
		boolean flag = false;
		InputStream is = null; 
		new MyAsynTask().execute();
		/*if(filename.equals("json"))
			is= context.getResources().openRawResource(R.raw.json);
		else if(filename.equals("json1"))
			is= context.getResources().openRawResource(R.raw.json1);
		else if(filename.equals("json2"))
			is= context.getResources().openRawResource(R.raw.json2);*/
		// read
		/*BufferedReader reader = new BufferedReader(new InputStreamReader(
				is, "utf-8"));
		String line = null;
		String data = "";
		while ((line = reader.readLine()) != null) {
			data += line;
		}
		is.close();

		*/
		
		return films;
	}
}
